package com.wwwarehouse.usercenter.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DeviceUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.response.ForgetPasswordResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;

import java.util.HashMap;
import java.util.Map;

import static com.wwwarehouse.usercenter.activity.LoginActivity.KEY_INPUT_USERNAME;

/**
 * Created by Jackie on 2017/6/27.
 * 忘记密码
 */

public class ForgetPasswordStep1Activity extends BaseActivity implements View.OnClickListener, TextWatcher, ClearEditText.onMyFocusChangeListener {
    private View mRootView;

    private ImageView mBackImg;
    private TextView mTitleTxt;

    private TextInputLayout mUsernameLayout;
    private ClearEditText mUsernameEdt;
    private TextInputLayout mCodeLayout;
    private ClearEditText mCodeEdt;
    private ImageView mCodeImg;

    private Button mNextBtn;

    private RequestQueue mRequestQueue;

    private final static int REQUEST_GET_VERIFICATION_IMAGE = 0;
    private final static int REQUEST_CHECK_IMAGE_CODE_SEND_SMS = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forget_password_1);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mRootView = findView(R.id.rl_root);

        mBackImg = findView(R.id.back_bt);
        mTitleTxt = findView(R.id.title_text);
        mTitleTxt.setText(R.string.forget_password_no_question_mark);

        mUsernameLayout = findView(R.id.til_username);
        mUsernameEdt = findView(R.id.et_username);
        mCodeLayout = findView(R.id.til_code);
        mCodeEdt = findView(R.id.et_code);
        mCodeImg = findView(R.id.iv_code);

        mNextBtn = findView(R.id.btn_next);

        mRequestQueue = NoHttp.newRequestQueue();
    }

    private void initData() {
        Intent intent = getIntent();

        if (intent != null) {
            String username = intent.getStringExtra(KEY_INPUT_USERNAME);
            mUsernameEdt.setText(username);
            mUsernameEdt.setSelection(username.length());
        }

        generateImageCode();
    }

    private void initEvent() {
        mRootView.setOnClickListener(this);

        mBackImg.setOnClickListener(this);

        mUsernameEdt.addTextChangedListener(this);
        mUsernameEdt.setOnMyFocusChangeListener(this);
        mCodeEdt.addTextChangedListener(this);
        mCodeEdt.setOnMyFocusChangeListener(this);
        mCodeImg.setOnClickListener(this);

        mNextBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.rl_root) {
          hideSoftKeyBoard(mRootView);
        } else if (id == R.id.back_bt) {
            finishActivity();
        } else if (id == R.id.iv_code) {
            generateImageCode();
        } else if (id == R.id.btn_next) {//验证手机号和图片验证码，同时发送短信验证码
            checkImageCodeSendSMS();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mUsernameEdt.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCodeEdt.getText().toString().trim())) {
            mNextBtn.setEnabled(true);
            mNextBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        } else {
            mNextBtn.setEnabled(false);
            mNextBtn.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view instanceof ClearEditText && hasFocus) {
            int id = view.getId();

            if (id == R.id.et_username) {
                mUsernameLayout.setStateNormal();
            } else if (id == R.id.et_code) {
                mCodeLayout.setStateNormal();
            }
        }
    }

    private void generateImageCode() {
        Map map = new HashMap();
        map.put("deviceInfo", DeviceUtils.getDeviceInfo(this));
        Request<byte[]> request = NoHttpUtils.getByteRequest(UserCenterConstant.URL_GET_IMAGE_VERIFICATION, map, RequestMethod.GET);

        //添加头信息
        String token = BaseApplication.sp.getValue(Constant.sp_Token);
        //auth_token必须传，不能为""，先随便写一个值
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("auth_token", token);
        } else {
            request.addHeader("auth_token", "10000");
        }
        request.addHeader("sign", "");
        request.addHeader("version", "1.0"); //服务端api版本
        request.addHeader("charset", "UTF-8");
        request.addHeader("w_appid", "wh_android_" + BaseApplication.getApplicationInstance().getVersionName());  //客户端版本描述
        request.setConnectTimeout(10 * 1000); // 设置连接超时
        request.setReadTimeout(20 * 1000); // 设置读取超时时间，也就是服务器的响应超时

        mRequestQueue.add(REQUEST_GET_VERIFICATION_IMAGE, request, new OnResponseListener<byte[]>() {
            @Override
            public void onStart(int what) {

            }

            @Override
            public void onSucceed(int what, Response<byte[]> response) {
                byte[] bytes = response.get();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                mCodeImg.setImageBitmap(bitmap);
            }

            @Override
            public void onFailed(int what, Response<byte[]> response) {
                LogUtils.showLog(response.getException().toString());
            }

            @Override
            public void onFinish(int what) {

            }
        });
    }

    private void checkImageCodeSendSMS() {
        Map map = new HashMap();
        map.put("deviceInfo", DeviceUtils.getDeviceInfo(this));
        map.put("userAccount", mUsernameEdt.getText().toString().trim());
        map.put("imageCode", mCodeEdt.getText().toString().trim());

        NoHttpUtils.httpPost(UserCenterConstant.URL_CHECK_IMAGE_CODE_SEND_SMS, map, mOnResponseListener, REQUEST_CHECK_IMAGE_CODE_SEND_SMS);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_CHECK_IMAGE_CODE_SEND_SMS:
                    if ("0".equals(commonClass.getCode())) {
                        //手机号和图片验证码验证通过
                        ForgetPasswordResponseBean forgetPasswordResponseBean = JSON.parseObject(commonClass.getData().toString(), ForgetPasswordResponseBean.class);

                        startActivity(ForgetPasswordStep2Activity.class, UserCenterConstant.KEY_LOGIN_MOBILE, forgetPasswordResponseBean.getMobile(), true);
                    } else if ("200016".equals(commonClass.getCode())) {  //200016 用户不存在
                        mUsernameLayout.setStateWrong(commonClass.getMsg());
                    } else if ("200026".equals(commonClass.getCode())) {  //200026 验证码错误
                        mCodeLayout.setStateWrong(commonClass.getMsg());
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {
            dismissProgress();
        }
    };
}
